<?php

/**
 * 独立app 微信登录
 */

namespace Login;


use custom\Log;
use think\Exception;

class WechatAlone {

    protected static $config = [
        'appid' => 'wx83ffbd4d3d50f6c1', //应用唯一标识，在微信开放平台提交应用审核通过后获得
        'secret' => '0e4fe3ce107dba0f19f985391dbd0b55', //应用密钥 AppSecret，在微信开放平台提交应用审核通过后获得
        'grant_type' => 'authorization_code', //填 authorization_code
    ];


    public static function request($params) {
        $config = self::$config;
        $config['code'] = $params['code'];
        $query = http_build_query($config);
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $get_token_url = $url . '?' . $query;
        $re= self::method($get_token_url,'POST');
        $res = json_decode($re, true);
        if (!isset($res['errcode'])) {
            return $res;
        }else{
            throw new Exception('微信授权失败');
        }

    }

    public static function getUserinfo($access_token,$openid){
        $config['access_token'] = $access_token;
        $config['openid'] = $openid;
        $query = http_build_query($config);
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $get_data = $url . '?' . $query;
        return self::method($get_data,'GET');
    }

    /**
     * 发送一个POST请求
     * @param string $url 请求URL
     * @param array $params 请求参数
     * @param array $options 扩展参数
     * @return mixed|string
     */
    public static function method($url,$method, $params = [], $options = []) {
        $req = self::sendRequest($url, $params, $method, $options);
        Log::write($req,'WechatAlone.log');
        return $req['ret'] ? $req['msg'] : '';
    }

    /**
     * CURL发送Request请求,含POST和REQUEST
     * @param string $url 请求的链接
     * @param mixed $params 传递的参数
     * @param string $method 请求的方法
     * @param mixed $options CURL的参数
     * @return array
     */
    public static function sendRequest($url, $params = [], $method = 'POST', $options = []) {
        $method = strtoupper($method);
        $protocol = substr($url, 0, 5);
        $query_string = is_array($params) ? http_build_query($params) : $params;
        $ch = curl_init();
        $defaults = [];
        if ('GET' == $method) {
            $geturl = $query_string ? $url . (stripos($url, "?") !== false ? "&" : "?") . $query_string : $url;
            $defaults[CURLOPT_URL] = $geturl;
        } else {
            $defaults[CURLOPT_URL] = $url;
            if ($method == 'POST') {
                $defaults[CURLOPT_POST] = 1;
            } else {
                $defaults[CURLOPT_CUSTOMREQUEST] = $method;
            }
            $defaults[CURLOPT_POSTFIELDS] = $query_string;
        }
        $defaults[CURLOPT_HEADER] = false;
        $defaults[CURLOPT_USERAGENT] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36";
        $defaults[CURLOPT_FOLLOWLOCATION] = true;
        $defaults[CURLOPT_RETURNTRANSFER] = true;
        $defaults[CURLOPT_CONNECTTIMEOUT] = 3;
        $defaults[CURLOPT_TIMEOUT] = 3;
        // disable 100-continue
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
        if ('https' == $protocol) {
            $defaults[CURLOPT_SSL_VERIFYPEER] = false;
            $defaults[CURLOPT_SSL_VERIFYHOST] = false;
        }
        curl_setopt_array($ch, (array)$options + $defaults);
        $ret = curl_exec($ch);
        $err = curl_error($ch);
        if (false === $ret || !empty($err)) {
            $errno = curl_errno($ch);
            $info = curl_getinfo($ch);
            curl_close($ch);
            return [
                'ret' => false,
                'errno' => $errno,
                'msg' => $err,
                'info' => $info,
            ];
        }
        curl_close($ch);
        return [
            'ret' => true,
            'msg' => $ret,
        ];
    }


}
